<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isRefreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <article-item
          v-for="(item, index) in list"
          :key="index"
          :article="item"
        ></article-item>
        <!-- <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title"
        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article";
import ArticleItem from "@/components/article-item/index.vue";
export default {
  name: "ArticleList",
  components: {
    ArticleItem,
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [], // 存储列表数据的数组
      loading: false, //控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      timestamp: null, //请求下一页的时间戳
      error: false, //若列表数据加载失败，将 error 设置成 true 即可显示错误提示
      isRefreshLoading: false,
      refreshSuccessText: "",
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(), //下拉刷线 每次请求获取最新数据 所以传递当前最新的时间戳
          with_top: 0, //是否包含置顶 进入页面一次请求时要包含置顶文章 1-包含置顶 0-不包含置顶
        });
        const { results } = data.data;
        this.list.push(...results);
        this.loading = false;
        if (results.length) {
          //更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp;
        } else {
          //没有数据了 将finished 设置为true 不在load 加载更多了
          this.finished = true;
        }
      } catch (err) {
        console.log("数据获取失败", err);
        this.error = true;
        this.loading = false;
      }
    },
    async onRefresh() {
      try {
        // 1. 请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道 id
          timestamp: Date.now(), // 下拉刷新每次都应该获取最新数据
          with_top: 1, // 是否包含置顶，进入页面第一次请求时要包含置顶文章，1-包含置顶，0-不包含
        });
        // 2. 将数据追加到列表的顶部
        const { results } = data.data;
        this.list.unshift(...results);
        // 3. 关闭下拉刷新的 loading 状态
        this.isRefreshLoading = false;
        //提示成功
        this.refreshSuccessText = `刷新成功,更新了${results.length}条数据`;
      } catch (err) {
        console.log(err);
        this.isRefreshLoading = false; // 关闭下拉刷新的 loading 状态
        this.$toast("刷新失败");
      }
    },
  },
};
</script>

<style scoped lang="less">
.artcile-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
